    //
//  PlayGameController.m
//  Quiz
//
//  Created by AnhLH-Oriolus on 28/07/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "PlayGameController.h"

#import "QuizAppDelegate.h"
#import "MainController.h"

@implementation PlayGameController

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
-(id)init{
	self = [super init];
	fTimeTick = 25.0;
	fCurrTick = 25.0;
	iCurrPoint = 0;
	iScore = 0;
	iCurrQuestion = 0;
	arrQuestion = [[NSMutableArray alloc] init];
	arrIdUsed = [[NSMutableArray alloc] init];
	arrOtherOptions = [[NSMutableArray alloc] init];
	
	return self;
}


// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
	UIImageView *v = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
	[v setImage:[UIImage imageNamed:@"images/backGround.png"]];
	[v setUserInteractionEnabled:YES];
	self.view = v;
	[v release];
	
//ViewnaviBar
	UIView *viewTopBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 60)];
	[viewTopBar setBackgroundColor:[UIColor colorWithWhite:0.8 alpha:0.8]];
	[self.view addSubview:viewTopBar];
	[viewTopBar release];
	
	//lblQuestIndex
	lblQuestionIndex = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
	[lblQuestionIndex setBackgroundColor:[UIColor clearColor]];
	lblQuestionIndex.textAlignment = UITextAlignmentCenter;
	lblQuestionIndex.text = @"Question: 1";
	lblQuestionIndex.font = [UIFont fontWithName:@"Arial" size:15];
	lblQuestionIndex.textColor = [UIColor darkGrayColor];
	[viewTopBar addSubview:lblQuestionIndex];
	[lblQuestionIndex release];
	
	//score
	lblScore = [[UILabel alloc] initWithFrame:CGRectMake(0, 25, 320, 40)];
	[lblScore setBackgroundColor:[UIColor clearColor]];
	lblScore.textAlignment = UITextAlignmentCenter;
	lblScore.text = @"Score: 0";
	lblScore.textColor = [UIColor whiteColor];
	lblScore.font = [UIFont fontWithName:@"Arial" size:20];
	[viewTopBar addSubview:lblScore];
	[lblScore release];
	
	[self initComponentQuiz];
}

-(void)initComponentQuiz{
	UIImageView *vClue = [[UIImageView alloc] initWithFrame:CGRectMake(20, 70, 280, 120)];
	vClue.image = [UIImage imageNamed:@"images/bkgrClue.png"];
	[self.view addSubview:vClue];
	[vClue release];
	//lblClue
	lblClue = [[UILabel alloc] initWithFrame:CGRectMake(2, 2, 278, 118)];
	[lblClue setBackgroundColor:[UIColor clearColor]];
	lblClue.textAlignment = UITextAlignmentCenter;
	lblClue.text = @"";
	lblClue.numberOfLines=6;
	lblClue.textColor = [UIColor whiteColor];
	lblClue.font = [UIFont fontWithName:@"Arial" size:16];
	[vClue addSubview:lblClue];
	[lblClue release];
	
	//lbl time
	//lblTime = [[UILabel alloc] initWithFrame:CGRectMake(140, 205, 80, 30)];
//	[lblTime setBackgroundColor:[UIColor clearColor]];
//	lblTime.textAlignment = UITextAlignmentCenter;
//	lblTime.text = @"Time: ";
//	lblTime.textColor = [UIColor whiteColor];
//	lblTime.font = [UIFont fontWithName:@"Arial" size:17];
//	[self.view addSubview:lblTime];
//	[lblTime release];
	//time decre
	lblTimeCountDown = [[FontLabel alloc] initWithFrame:CGRectMake(0, 200, 320, 30) fontName:@"scoreboard" pointSize:40];
	[lblTimeCountDown setBackgroundColor:[UIColor clearColor]];
	lblTimeCountDown.textAlignment = UITextAlignmentCenter;
	lblTimeCountDown.textColor = [UIColor blueColor];
	[self.view addSubview:lblTimeCountDown];
	[lblTimeCountDown release];
	
	
	//answerA
	viewSelectA = [[ViewSelect alloc] initWithFrame:CGRectMake(20, 240, 280, 40)];
	[viewSelectA setBackgroundColor:[UIColor clearColor]];
	[viewSelectA setLblOption:@"A."];
	[self.view addSubview:viewSelectA];
	[viewSelectA release];
	
	btnAnswerA = [[UIButton alloc] initWithFrame:CGRectMake(20, 240, 280, 40)];
	[btnAnswerA setBackgroundColor:[UIColor clearColor]];
	[btnAnswerA addTarget:self action:@selector(onSelectAnswer:) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:btnAnswerA];
	[btnAnswerA release];
	
	//answerB
	viewSelectB = [[ViewSelect alloc] initWithFrame:CGRectMake(20, 240+40+10, 280, 40)];
	[viewSelectB setBackgroundColor:[UIColor clearColor]];
	[viewSelectB setLblOption:@"B."];
	[self.view addSubview:viewSelectB];
	[viewSelectB release];
	
	btnAnswerB = [[UIButton alloc] initWithFrame:CGRectMake(20, 240+40+10, 280, 40)];
	[btnAnswerB setBackgroundColor:[UIColor clearColor]];
	[btnAnswerB addTarget:self action:@selector(onSelectAnswer:) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:btnAnswerB];
	[btnAnswerB release];
	
	//answerC
	viewSelectC = [[ViewSelect alloc] initWithFrame:CGRectMake(20, 240+40*2+20, 280, 40)];
	[viewSelectC setBackgroundColor:[UIColor clearColor]];
	[viewSelectC setLblOption:@"C."];
	[self.view addSubview:viewSelectC];
	[viewSelectC release];
	
	btnAnswerC = [[UIButton alloc] initWithFrame:CGRectMake(20, 240+40*2+20, 280, 40)];
	[btnAnswerC setBackgroundColor:[UIColor clearColor]];
	[btnAnswerC addTarget:self action:@selector(onSelectAnswer:) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:btnAnswerC];
	[btnAnswerC release];
	
	//answerD
	viewSelectD = [[ViewSelect alloc] initWithFrame:CGRectMake(20, 240+40*3+30, 280, 40)];
	[viewSelectD setBackgroundColor:[UIColor clearColor]];
	[viewSelectD setLblOption:@"D."];
	[self.view addSubview:viewSelectD];
	[viewSelectD release];
	
	btnAnswerD = [[UIButton alloc] initWithFrame:CGRectMake(20, 240+40*3+30, 280, 40)];
	[btnAnswerD setBackgroundColor:[UIColor clearColor]];
	[btnAnswerD addTarget:self action:@selector(onSelectAnswer:) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:btnAnswerD];
	[btnAnswerD release];
}

-(void)onSelectAnswer:(id)sender{
	iCurrPoint = fCurrTick * 10;
	NSLog(@"curr point %d",iCurrPoint);
	
	UIButton *btn = (UIButton *)sender;
	
	if(btn == btnAnswerA){
		[viewSelectA showCheck:YES];
		[viewSelectB showCheck:NO];
		[viewSelectC showCheck:NO];
		[viewSelectD showCheck:NO];
	}
	
	if(btn == btnAnswerB){
		[viewSelectA showCheck:NO];
		[viewSelectB showCheck:YES];
		[viewSelectC showCheck:NO];
		[viewSelectD showCheck:NO];
	}
	
	if(btn == btnAnswerC){
		[viewSelectA showCheck:NO];
		[viewSelectB showCheck:NO];
		[viewSelectC showCheck:YES];
		[viewSelectD showCheck:NO];
	}
	
	if(btn == btnAnswerD){
		[viewSelectA showCheck:NO];
		[viewSelectB showCheck:NO];
		[viewSelectC showCheck:NO];
		[viewSelectD showCheck:YES];
	}
	
}


-(void)initTimer{
	if (timer) {
		[timer invalidate];
		timer = nil;
	}
	
	timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(decreaseTime:) userInfo:nil repeats:YES];
}

-(void)decreaseTime:(NSTimer *)time{
	fCurrTick = fCurrTick - 0.1;
	//progressView.progress = fCurrTick/fTimeTick;
	lblTimeCountDown.text = [NSString stringWithFormat:@"%.1f", fCurrTick];
	
	int tempValue = fCurrTick *10;
	if(tempValue == 200){
		lblClue.text = [NSString stringWithFormat:@"%@", [arrQuestion objectAtIndex:3]];
	}
	if(tempValue == 150){
		lblClue.text = [NSString stringWithFormat:@"%@", [arrQuestion objectAtIndex:4]];
	}
	if(tempValue == 100){
		lblClue.text = [NSString stringWithFormat:@"%@", [arrQuestion objectAtIndex:5]];
	}
	if(tempValue == 50){
		lblClue.text = [NSString stringWithFormat:@"%@", [arrQuestion objectAtIndex:6]];
	}
	
	if(tempValue == 0){
		[timer invalidate];
		timer = nil;
		[self checkAnswer];
	}
}

-(void)checkAnswer{
	NSString *strAnswer = @"";
	
	if(viewSelectA.isCheckOption){
		strAnswer = [viewSelectA getText];
	}
	if(viewSelectB.isCheckOption){
		strAnswer = [viewSelectB getText];
	}
	if(viewSelectC.isCheckOption){
		strAnswer = [viewSelectC getText];
	}
	if(viewSelectD.isCheckOption){
		strAnswer = [viewSelectD getText];
	}
	
	if([strAnswer isEqualToString:@""] || ![strAnswer isEqualToString:[arrQuestion objectAtIndex:1]])
	{
		[self endGame];
	}
	else {
		iScore = iScore + iCurrPoint;
		lblScore.text = [NSString stringWithFormat:@"Score: %d", iScore];
		[self renegateQuestion];
		fCurrTick = 25.0;
	}

	
}

//load du lieu trong csdl
-(BOOL)openDb{
	NSString *path = [NSString stringWithFormat:@"%@/FootballTeam.db",g_strMainBundlePath];
	db = [FMDatabase databaseWithPath:path];
    if (![db open]) {
        NSLog(@"Could not open db.");
		return FALSE;
    }
	NSLog(@"DB opened successfully");
	return TRUE;
}

-(void)resetAllData{
	[viewSelectA setLblOption:@""];
	[viewSelectB setLblOption:@""];
	[viewSelectC setLblOption:@""];
	[viewSelectD setLblOption:@""];
	
	[viewSelectA showCheck:NO];
	[viewSelectB showCheck:NO];
	[viewSelectC showCheck:NO];
	[viewSelectD showCheck:NO];
	
	lblClue.text = @"";
	lblScore.text = @"Score: 0";
	lblQuestionIndex.text = @"Question: 0";
	
	iCurrPoint = 0;
	iCurrQuestion = 0;
	fCurrTick = 25.0;
	iScore = 0;
	
	[arrIdUsed removeAllObjects];
	//tinh tong so luong cau hoi
	[self getTotalNumberQuestion];
	//sinh cau hoi dau tien
	[self renegateQuestion];
}

-(void)getTotalNumberQuestion{
	[self openDb];
	FMResultSet *rs = [db executeQuery:@"select count(TeamID) as Total from Team"];	
	while( [rs next])
	{
		iTotalQuestion = [rs intForColumn:@"Total"];
	}
	[rs close];
	[self closeDb];
	NSLog(@"%d", iTotalQuestion);
}

-(void)renegateQuestion{
	[self openDb];
	
	srandom(time(0));
	
	int idxRandom = random() % iTotalQuestion + 1;
	
	while (1) {
		if([arrIdUsed count] == (iTotalQuestion - 1))// tra loi het cac cau hoi roi thi end game
		{
			[self endGame];
			return;
		}
		
		BOOL isUsedId = FALSE;
		
		for (int i = 0; i < [arrIdUsed count]; i++) {
			int idUsed = [[arrIdUsed objectAtIndex:i] intValue];
			
			if(idxRandom == idUsed){ // da su dung id nay de lam cau hoi
				isUsedId = TRUE;
				break;
			}
		}
		
		if(isUsedId){
			idxRandom = random() % iTotalQuestion + 1;
		}else {
			break;
		}
	}
	
	NSLog(@"ran %d", idxRandom);
	//add vao mang arrIdUsed
	[arrIdUsed addObject:[NSNumber numberWithInt:idxRandom]];
	//get info
	NSString *sql = [NSString stringWithFormat:@"SELECT TeamID, TeamName FROM Team WHERE TeamID = %d", idxRandom];
	FMResultSet *rs = [db executeQuery:sql];
	
	[arrQuestion removeAllObjects];
	while( [rs next])
	{
		int index = [rs intForColumn:@"TeamID"];
		NSString *teamName = [rs stringForColumn:@"TeamName"];
		NSLog(@"ans : %@", teamName);
		[arrQuestion addObject:[NSNumber numberWithInt:index]];
		[arrQuestion addObject:teamName];
		break;
	}
	[rs close];
	
	sql = [NSString stringWithFormat:@"SELECT ClueDetail FROM Clue WHERE TeamID = %d", idxRandom]; 
	rs = [db executeQuery:sql];
	while( [rs next])
	{
		NSString *clueDetail = [rs stringForColumn:@"ClueDetail"];
		[arrQuestion addObject:clueDetail];
	}
	[rs close];
	
#pragma mark renegate 3 option
	int idOptionRandom1 = random() % iTotalQuestion + 1;
	int idOptionRandom2 = random() % iTotalQuestion + 1;
	int idOptionRandom3 = random() % iTotalQuestion + 1;
	while (1) {
		if(idOptionRandom1 != idxRandom && idOptionRandom2 != idxRandom && idOptionRandom3 != idxRandom){
			if(idOptionRandom1 != idOptionRandom2 && idOptionRandom1 != idOptionRandom3 && idOptionRandom2 != idOptionRandom3){
				break;
			}
		}
		idOptionRandom1 = random() % iTotalQuestion + 1;
		idOptionRandom2 = random() % iTotalQuestion + 1;
		idOptionRandom3 = random() % iTotalQuestion + 1;
	}
	//get 3 option
	sql = [NSString stringWithFormat:@"SELECT TeamName FROM Team WHERE TeamID in (%d, %d, %d)", idOptionRandom1,idOptionRandom2,idOptionRandom3]; 
	rs = [db executeQuery:sql];
	[arrOtherOptions removeAllObjects];
	while( [rs next])
	{
		NSString *teamNameOption = [rs stringForColumn:@"TeamName"];
		NSLog(@"not ans: %@", teamNameOption);
		[arrOtherOptions addObject:teamNameOption];
	}
	[rs close];
	
	//add them cau tra loi vao mang option
	[arrOtherOptions addObject:[arrQuestion objectAtIndex:1]];
	//hien thi
	[self disPlayQuestion];
	
	[self closeDb];
}

-(void)disPlayQuestion{
	srandom(time(0)); 
	int iTotalOptions = 4;
	int idOptionRandom1 = random() % iTotalOptions;
	int idOptionRandom2 = random() % iTotalOptions;
	int idOptionRandom3 = random() % iTotalOptions;
	int idOptionRandom4 = random() % iTotalOptions;
	
	while (1) {
		if(idOptionRandom1 != idOptionRandom2 && idOptionRandom1 != idOptionRandom3 && idOptionRandom1 != idOptionRandom4 && idOptionRandom2 != idOptionRandom3 && idOptionRandom2 != idOptionRandom4 && idOptionRandom3 != idOptionRandom4){
			break;
		}
		
		idOptionRandom1 = random() % iTotalOptions;
		idOptionRandom2 = random() % iTotalOptions;
		idOptionRandom3 = random() % iTotalOptions;
		idOptionRandom4 = random() % iTotalOptions;
	}
	
	[viewSelectA setLblOption:[NSString stringWithFormat:@"%@", [arrOtherOptions objectAtIndex:idOptionRandom1]]];
	[viewSelectB setLblOption:[NSString stringWithFormat:@"%@", [arrOtherOptions objectAtIndex:idOptionRandom2]]];
	[viewSelectC setLblOption:[NSString stringWithFormat:@"%@", [arrOtherOptions objectAtIndex:idOptionRandom3]]];
	[viewSelectD setLblOption:[NSString stringWithFormat:@"%@", [arrOtherOptions objectAtIndex:idOptionRandom4]]];
	
	[viewSelectA showCheck:NO];
	[viewSelectB showCheck:NO];
	[viewSelectC showCheck:NO];
	[viewSelectD showCheck:NO];
	
	iCurrQuestion++;
	lblClue.text = [NSString stringWithFormat:@"%@", [arrQuestion objectAtIndex:2]];
	lblScore.text = [NSString stringWithFormat:@"Score: %d", iScore];
	lblQuestionIndex.text = [NSString stringWithFormat:@"Question: %d", iCurrQuestion];
	
	[self initTimer];
}

-(void)endGame{
	NSLog(@"%@ - %d", sName, iScore);
	UIAlertView *al = [[UIAlertView alloc] initWithTitle:playerName message:[NSString stringWithFormat:@"%d",iScore] delegate:self cancelButtonTitle:nil otherButtonTitles:@"Play again",@"Update score",@"Go main menu",nil];
	[al show];
	[al release];
}

- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
	if(buttonIndex == 0){
		NSLog(@"Play again");
		[self updateOwnScore];
		[self resetAllData];
	}
	if(buttonIndex == 1){
		NSLog(@"Update score");
		[self updateOwnScore];
		NSLog(@"%@ - %d", playerName, iScore);
		[g_AppDelegate.mainCtrl goToScoreWithMode:1 ofPlayerName:playerName andScore:iScore];
	}
	if(buttonIndex == 2){
		NSLog(@"Go main menu");
		[self updateOwnScore];
		[self.view removeFromSuperview];
		[g_AppDelegate.mainCtrl openMenuViewCtrl];
	}
}

-(void)updateOwnScore{
	//insert score to own player
	
	if([self openDb]){
		int index = -1;
		NSString *sql = [NSString stringWithFormat:@"select PlayerID from Player where PlayerName like '%@'",sName];
		FMResultSet *rs = [db executeQuery:sql];
		
		while( [rs next])
		{
			index = [rs intForColumn:@"PlayerID"];
			break;
		}
		[rs close];

		int iTotalScore = 0;
		rs = [db executeQuery:@"select max(ScoreID) as Total from Score where Mode = 0"];	
		while([rs next])
		{
			iTotalScore = [rs intForColumn:@"Total"];
		}
		[rs close];
		
		if(index == -1){
			[self closeDb];
			return;
		}
		
		sql = [NSString stringWithFormat:@"insert into Score values(0,%d,%d,%d)", index, iScore, iTotalScore+1];
		[db beginTransaction];
		[db executeUpdate:sql];
		[db commit];
		
		[self closeDb];
	}
	[self closeDb];
}

-(void)closeDb{
	
    if (db && [db open]) {
		[db close];
    }
}

-(void)setPlayerName:(NSString *)name{
	playerName = [name retain];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
